﻿@using Gurux.DLMS.AMI.Script
@using Gurux.DLMS.AMI.Shared
@using Gurux.DLMS.AMI.Shared.DIs

@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Gurux.DLMS.AMI.Shared.Enums
@using Gurux.DLMS.AMI.Module
@using System.Globalization
@using System.Text
@using System.Text.Json
@using Gurux.DLMS.AMI.Script.Pages
@using Microsoft.AspNetCore.SignalR.Client
@using Microsoft.Extensions.Logging

@namespace Gurux.DLMS.AMI.Client.Pages.Config

@inject NavigationManager NavigationManager
@implements IDisposable
@implements IGXConfigUpdate

@inject HttpClient Http
@inject IGXNotifier Notifier

@if (_settings != null)
{
    <EditForm Model="@_settings">
        <div class="row">
            <div style="width:100%">
                <div class="form-group">
                    <label>Size of the database connection pool</label>
                    <InputNumber id="poolSize" class="form-control"
                             @bind-Value="_settings.PoolSize" />
                </div>
                <div class="form-group">
                    <InputCheckbox id="useSwagger" @bind-Value="_settings.UseSwagger" />
                    <label>@Properties.Resources.EnableSwagger</label>
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.SiteEmailAddress</label>
                    <InputText id="siteEmailAddress" class="form-control"
                           @bind-Value="_settings.SiteEmailAddress" />
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.RowsPerPage</label>
                    <select class="form-select" @bind="_settings.RowsPerPage">
                        @foreach (var it in RowsPerPage)
                        {
                            <option value="@it">@it</option>
                        }
                    </select>
                </div>
            </div>
        </div>
        <button type="button" style="float: right;" class="btn btn-danger"
            @onclick="() => OnRestart()">
            Restart
        </button>
    </EditForm>
}

@code {
    int[] RowsPerPage = new int[] { 10, 20, 50, 100 };

    /// <inheritdoc/>
    public void Update()
    {
        if (string.IsNullOrEmpty(Parent?.Active?.Settings))
        {
            _settings = new SystemSettings();
        }
        else
        {
            _settings = JsonSerializer.Deserialize<SystemSettings>(Parent.Active.Settings);
        }
        StateHasChanged();
    }

    /// <summary>
    /// Parent component.
    /// </summary>
    [Parameter]
    public Gurux.DLMS.AMI.Client.Pages.Config.Configurations? Parent { get; set; }

    SystemSettings? _settings;

    protected override void OnInitialized()
    {
        try
        {
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            Notifier.On<IEnumerable<GXConfiguration>>(this, nameof(IGXHubEvents.ConfigurationSave), async (configurations) =>
            {
                if (configurations != null)
                {
                    foreach (var it in configurations)
                    {
                        if (it.Name == GXConfigurations.System && !string.IsNullOrEmpty(it.Settings))
                        {
                            _settings = JsonSerializer.Deserialize<SystemSettings>(it.Settings);
                            StateHasChanged();
                            break;
                        }
                    }
                }
            });
            Notifier.Clear();
            Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Save, Icon = "oi oi-pencil", OnClick = OnSave });
            Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Cancel, Icon = "oi oi-action-undo", OnClick = OnCancel });
            Notifier.UpdateButtons();
            if (string.IsNullOrEmpty(Parent?.Active?.Settings))
            {
                _settings = new SystemSettings();
            }
            else
            {
                _settings = JsonSerializer.Deserialize<SystemSettings>(Parent.Active.Settings);
            }
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Save values.
    /// </summary>
    private async void OnSave()
    {
        try
        {
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            if (Parent?.Active == null)
            {
                throw new Exception(Properties.Resources.InvalidTarget);
            }
            Parent.Active.Settings = JsonSerializer.Serialize(_settings);
            ConfigurationUpdate arg = new ConfigurationUpdate();
            arg.Configurations = new GXConfiguration[] { Parent.Active };
            await Http.PostAsJson<ConfigurationUpdateResponse>("api/Configuration/Update", arg);
            ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Restart the application.
    /// </summary>
    private async void OnRestart()
    {
        Notifier?.ProgressStart();
        Notifier?.ClearStatus();
        try
        {
            StopApplicationRequest req = new StopApplicationRequest();
            await Http.PostAsJson("api/Configuration/Restart", req);
            Notifier?.ShowInformation("System restarted.");
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Cancel update.
    ///</summary>
    private void OnCancel()
    {
        ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
    }

    public void Dispose()
    {
        Notifier.RemoveListener(this);
    }
}
